#include "command.h"

int _cat(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 2) {
		fprintf(stderr, "Usage: cat [file]\n");
		return -1;
	}

    // If a file argument is provided, open it; otherwise, use stdin
	int fd;
    if (argc == 2) {
        const char *file = argv[1];
        fd = open(file, O_RDONLY);
        if (fd == -1) {
            fprintf(stderr, "cat error: open\n");
            return -1;
        }
    } else {
        fd = STDIN_FILENO; // No file provided, use standard input
    }
	
	/* read the content to buffer and write to stdout */
	lseek(fd, 0, SEEK_SET);
	int num_read = 0;
	char buf[BUF_SIZE];

	while ((num_read = read(fd, buf, BUF_SIZE)) > 0) {
			write(STDOUT_FILENO, buf, num_read);
	}
	if (fd != STDIN_FILENO)
		close(fd);

	if (num_read == -1) {
		fprintf(stderr, "cat error: read\n");
		return -1;
	}

	return 0;
}
